"use strict";
const Service = require("egg").Service;
const { Op } = require("sequelize");

const { failRes, successRes } = require("../extend/helper");
const { Journal } = require("../exception/Journal");
const Classes = require("../model/Classes");

function toInt(str) {
  if (typeof str === "number") return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class sOrders extends Service {
  // pc
  // 订单查询
  async pc_s_query(params) {
    console.log("paramsOrders:===============> ", params);
    let response = null;
    const { ctx } = this;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);
      // const uid = (params?.uid ?? "");
      let where = {
        status: {
          [Op.like]: `%${params?.status ?? ""}%`, // 使用 Op.like 实现模糊匹配
        },
        id: {
          [Op.like]: `%${params?.id ?? ""}%`, // 使用 Op.like 实现模糊匹配
        },
      };
      const counts = await ctx.model.Orders.count({ where });
      const result = await ctx.model.Orders.findAndCountAll({
        where,
        include: [
          // 关联查询商品分类表
          {
            model: ctx.model.Products,
            // required: true, // 设置为必须关联查询
            attributes: ["id", "title", "price", "defaultImg"], // 指定查询的字段
            // through: { attributes: [] },
            through: { attributes: ["pcount"] },
          },
          {
            model: ctx.model.Address,
            // required: true, // 设置为必须关联查询
            attributes: [
              "id",
              "nickName",
              "mobile",
              "provincial",
              "city",
              "address",
              "uid",
            ], // 指定查询的字段
          },
          {
            model: ctx.model.Users,
            where: {
              userName: {
                [Op.like]: `%${params?.userName ?? ""}%`, // 使用 Op.like 实现模糊匹配
              }
            }
          },
        ],
        order: [["updatedAt", "DESC"]], // 排序
        attributes: ["id", "uid", "status", "totals","remark", "coupon_totals", "createdAt", "updatedAt"],
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      });
      console.log(result, "<---- 商品订单查询结果 - 商品订单查询");
      await Journal(ctx, { operatorType: "商品订单 -> 查询", code: 200 });
      response = successRes({
        records: result?.rows ?? [],
        total: counts || 0,
        pageSize,
        currentPage,
      });
    } catch (error) {
      console.error(error, "<---- error - 商品订单查询");
      await Journal(ctx, { operatorType: "商品订单 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 订单状态更新
  async pc_s_update_orders(params) {
    let response = null;
    let transaction;
    const { ctx } = this;
    try {
      // 建立事务对象
      transaction = await ctx.model.transaction();
     
      await ctx.model.Orders.update(
        params,
        {
          where: { id: params.id },
          attributes: { extends: ['id'] }
        },
        { transaction }
      );
      await transaction.commit();
      await Journal(ctx, { operatorType: '订单更新 -> 编辑', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 订单更新编辑');
      await transaction.rollback();
      await Journal(ctx, { operatorType: '订单更新 -> 编辑', code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 订单删除
  async pc_s_delete_orders(params) {
    let response = null;
    try {
      const { ctx } = this;
      await ctx.model.Orders.destroy(
        {
          where: { id: params.id },
        }
      );
      await Journal(ctx, { operatorType: '订单删除 -> 删除', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 订单删除删除');
      await Journal(ctx, { operatorType: '订单删除 -> 删除', code: 401 });
      response = failRes(401);
    }
    return response;
  }


  // 用户单个订单查询
  async wa_s_queryOrders(params) {
      let response = null;
      const { ctx } = this;
      try {
          const result = await ctx.model.Orders.findOne({
            where: {
              id: params?.id ?? "",
            },
            include: [
              {
                model: ctx.model.Products,
              },
              {
                model: ctx.model.Address,
              },
              {
                model: ctx.model.Users,
              },
            ],
          });
          await Journal(ctx, { operatorType: '订单信息 -> 查询', code: 200 });
          response = successRes(result);
      } catch (error) {
          console.error(error, '<---- error - 订单信息查询');
          await Journal(ctx, { operatorType: '订单信息 -> 查询', code: 401 });
          response = failRes(401);
      }
      return response;
  }

  //用户订单操作
  async wa_s_operateOrders(params) {
    console.log(params, '<---- params - 订单操作');
    let response = null;
    const { ctx } = this;
    let transaction;

    try {
      transaction = await ctx.model.transaction();
    
      await ctx.model.Orders.update(params, {
          where: { id: params.id },
          attributes: ['status'] ,
      },
      { transaction }
      );
      await Journal(ctx, { operatorType: '订单信息 -> 操作', code: 200 });
      response = successRes();

    }catch (error) {
      await transaction.rollback();
      console.error(error, '<---- error - 订单信息操作');
      response = failRes(401);
    }
    return response;
  }

  //用户立即支付
  async wa_s_payOrders(params) {
    console.log(params, '<---- params - 用户立即支付');
    let response = null;
    const { ctx } = this;
    let transaction;

    try {
      transaction = await ctx.model.transaction();
      const userTotals = await ctx.model.Users.findOne({
        where: { id: params?.uid },
        attributes: ['id', 'totals'],
      })
      console.log(userTotals.totals, '<---- userTotals - 用户原本余额');
      if((userTotals.totals - params.order_totals) >= 0){
        await userTotals.update({ totals: (userTotals.totals - params.order_totals)});

        console.log(params.order_totals, '<---- userTotals - 用户支付金额');

        console.log(userTotals.totals, '<---- userTotals - 用户支付后余额');

      }else{
        console.log("余额不足");
        throw new Error(288);
      }

     
      await Journal(ctx, { operatorType: '订单信息 -> 操作', code: 200 });
      response = successRes();

    }catch (error) {
      await transaction.rollback();
      console.error(error, '<---- error - 订单信息操作');
      response = failRes(401);
    }
    return response;
  }


  // 用户订单删除
  async wa_s_delete_orders(params) {
    let response = null;
    try {
      const { ctx } = this;
      await ctx.model.Orders.destroy(
        {
          where: { id: params.order_id },
        }
      );
      await Journal(ctx, { operatorType: '订单删除 -> 删除', code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, '<---- error - 订单删除删除');
      await Journal(ctx, { operatorType: '订单删除 -> 删除', code: 401 });
      response = failRes(401);
    }
    return response;
  }
  

}

module.exports = sOrders;
